let id = 0;

const container = document.getElementsByTagName("head")[0];

const jsonp = options => {
  if (!options || !options.url) return;

  const scriptNode = document.createElement('script'),
    data = options.data || {},
    callback = options.callback,
    fnName = `json${id++}`

  let url = options.url;

  // 添加回调函数
  data['callback'] = fnName;

  // 拼接url
  const params = [];
  for (const key in data) {
    params.push(`${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`);
  };

  url = url.indexOf('?') > 0 ? (url + '&') : (url + '?');
  url += params.join('&');

  scriptNode.src = url;

  window[fnName] = (result) => {
    callback && callback(result);
    container.removeChild(scriptNode);
    delete window[fnName];
  };

  // 错误处理
  scriptNode.onerror = () => {
    callback && callback({
      error: 'error'
    });
    container.removeChild(scriptNode);
    window[fnName] && delete window[fnName];
  };

  scriptNode.type = 'text/javascript';
  container.appendChild(scriptNode);
};

window['jsonp'] = jsonp;